<template>
  <div>
    <ul v-for="(item,index) in imageList" :key="index" class="el-upload-list el-upload-list--picture-card">
      <li tabindex="0" class="el-upload-list__item is-ready" :style="'width:' + width + 'px;height:' + height +'px'">
        <div>
          <img :src="item" :alt="item" class="el-upload-list__item-thumbnail">
          <span class="el-upload-list__item-actions">
            <span v-if="index !== 0" class="el-upload-list__item-preview" @click="moveForward(index)">
              <i class="el-icon-back"/>
            </span>
            <span class="el-upload-list__item-preview" @click="preview(index)">
              <i class="el-icon-view"/>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="removeImg(index)">
              <i class="el-icon-delete"/>
            </span>
            <span v-if="index !== imageList.length - 1" class="el-upload-list__item-preview" @click="moveBack(index)">
              <i class="el-icon-right"/>
            </span>
          </span>
        </div>
      </li>
    </ul>

    <div v-if="num > imageList.length && !disabled" class="el-upload el-upload--picture-card li-item"
         @click="showImgLibrary" :style="'width: ' + width + 'px;height: ' + height + 'px;'+'line-height:' + height +'px;'"
    >
      <i class="el-icon-plus"/>
    </div>

    <el-dialog
      title="图片素材库"
      :close-on-click-modal="false"
      append-to-body
      :visible.sync="imageLibraryVisible"
      width="80%"
    >
      <el-row>
        <el-col :span="4">
          <div class="tab-pane-box">
            <div style="margin-bottom: 10px;margin-left: 30px">
              <el-button
                class="el-icon-plus"
                size="small"
                @click="categoryAdd()"
              >
                添加分组
              </el-button>
            </div>
            <el-tabs tab-position="left" style="float:right;" @tab-click="tabClick">
              <el-tab-pane
                v-model="activeName"
                :label="item.name"
                v-for="(item,index) in imgCategory"
                :key="index"
              ></el-tab-pane>
            </el-tabs>
          </div>
        </el-col>
        <el-col :span="19" :push="1">
          <el-card>
            <div slot="header" style="height: 30px">
              <span style="float: left;padding: 6px 0">{{ category.name }}</span>
              <el-button
                style="float: left;margin-left: 10px"
                type="text"
                class="el-icon-edit"
                size="small"
                @click="editImageCategory"
              >重命名
              </el-button>
              <el-button
                style="float: left;margin-left: 10px;color: red"
                type="text"
                class="el-icon-delete"
                size="small"
                @click="removeImageCategory"
              >删除
              </el-button>
              <div style="float: right">
                <el-upload
                  :action="uploadImgUrl"
                  :headers="headers"
                  :file-list="[]"
                  :before-upload="beforeUpload"
                  :on-success="handleSuccess"
                  :data="{cateId:''}"
                  multiple
                >
                  <el-button size="mini" type="primary">批量上传</el-button>
                </el-upload>
              </div>
            </div>
            <div class="img-card-box">
              <el-alert
                v-if="dataSource.length <= 0"
                title="暂无数据"
                type="info"
                :closable="false"
                center
                show-icon
              />
              <el-checkbox-group v-model="selectedImages" :max="num">
                <el-card class="img-card-item" v-for="(img,idx) in dataSource" :key="idx">
                  <image-preview
                    height="90px"
                    :src="img.path"
                    style="width: 100%;"
                    v-if="!img.path.endsWith('.mp4')"></image-preview>
                  <video
                    width="100px"
                    height="100px"
                    v-else
                    controls="controls"
                    autoplay="autoplay"
                    ref="video"
                    muted="muted"
                    :src="img.path">
                  </video>
                  <div class="card-footer">
                    <el-row>
                      <el-col :span="12" style="line-height: 35px">
                        <el-checkbox :label="img.path">选择
                        </el-checkbox>
                      </el-col>
                      <el-col :span="12" style="line-height: 30px">
                        <el-button @click="deleteImg(img.id)" type="text" style="color: red">删除</el-button>
                      </el-col>
                    </el-row>
                  </div>
                </el-card>
              </el-checkbox-group>
            </div>
            <el-pagination
              :current-page.sync="queryParams.pageNum"
              :page-sizes="[8,12, 16]"
              :page-size="queryParams.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="queryParams.total"
              class="pagination"
              @size-change="sizeChange"
              @current-change="pageChange"
            />
          </el-card>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
          <el-button @click="imageLibraryVisible = false" size="mini">取 消</el-button>
          <el-button type="primary" @click="confirmSelect" size="mini">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      append-to-body
      :visible.sync="previewVisible"
      width="35%"
    >
      <img :src="url" alt="" style="width: 100%">
    </el-dialog>
  </div>
</template>

<script>

import {getToken} from '@/utils/auth'
import {addAttach, attachPage, deleteAttach} from '@/api/system/attach'
import {addAttachCate, attachCateList, delAttachCate, updateAttachCate} from '@/api/system/attachCate'

export default {
  name: 'MaterialLibrary',
  props: {
    disabled: {
      type: Boolean,
      default() {
        return false
      }
    },
    num: {
      type: Number,
      default() {
        return 5
      }
    },
    type: {
      type: String,
      default() {
        return 'text'
      }
    },
    width: {
      type: Number,
      default() {
        return 150
      }
    },
    height: {
      type: Number,
      default() {
        return 150
      }
    },
    value: {
      type: [String, Array]
    }
  },
  data() {
    return {
      url: '',
      queryParams: {
        total: 0,
        pageNum: 1,
        pageSize: 8
      },
      imageLibraryVisible: false,
      previewVisible: false,
      activeName: '全部分组',
      uploadImgUrl: process.env.VUE_APP_BASE_API + '/console/system/attach/upload',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      imageList: [],
      dataSource: [],
      imgCategory: [],
      selectedImages: [],
      category: ''
    }
  },
  watch: {
    value: {
      handler(cv, ov) {
        if (this.type === 'text') {
          if (typeof this.value === 'string' && this.value !== '') {
            this.imageList = this.value.split(',')
            this.selectedImages = [...this.imageList]
          }
        }
        if (this.type === 'list') {
          if (this.value && this.value.length > 0) {
            this.imageList = this.value
            this.selectedImages = [...this.imageList]
          }
        }
      },
      deep: true,
      immediate: true
    },
  },
  methods: {
    moveForward(index) {
      let tmp = this.imageList[index - 1]
      this.$set(this.imageList, index - 1, this.imageList[index])
      this.$set(this.imageList, index, tmp)
    },
    moveBack(index) {
      let tmp = this.imageList[index + 1]
      this.$set(this.imageList, index + 1, this.imageList[index])
      this.$set(this.imageList, index, tmp)
    },
    removeImg(index) {
      let splice = this.imageList.splice(index, 1);
      let idx = this.selectedImages.indexOf(splice[0]);
      if (idx !== -1) {
        this.selectedImages.splice(idx, 1)
      }
    },
    deleteImg(id) {
      deleteAttach(id).then(res => {
        this.getAttach()
        this.$message.success('图片已删除')
      })
    },
    showImgLibrary() {
      this.getCategory()
      this.imageLibraryVisible = true
    },
    getCategory() {
      attachCateList().then(response => {
        let data = response.data
        data.unshift({
          id: '0',
          name: '全部分组'
        })
        this.imgCategory = data
        if (this.category) {
          console.log(this.category)
          let idx = this.imgCategory.findIndex(item => item.id === this.category.id);
          if (idx !== -1) {
            this.tabClick({index: idx})
          }
        } else {
          this.getAttach()
          this.tabClick({
            index: 0
          })
        }
      })
    },
    categoryAdd() {
      const that = this
      this.$prompt('请输入分组名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({value}) => {
        addAttachCate({
          name: value
        }).then(res => {
          that.getCategory()
        })
      })
    },
    tabClick(tab) {
      let index = parseInt(tab.index)
      if (index === 0) {
        delete this.queryParams.cateId
        this.getAttach()
        return
      }
      let cate = this.imgCategory[index]
      this.category = cate
      this.queryParams.cateId = cate.id
      this.getAttach()
    },
    confirmSelect() {
      this.imageList = [...this.selectedImages]
      if (this.type === 'list') {
        this.$emit('change', this.imageList)
      } else {
        let value = this.imageList.join(',');
        this.$emit('change', value)
      }
      this.imageLibraryVisible = false
    },
    sizeChange(val) {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = val
      this.getAttach()
    },
    pageChange(val) {
      this.queryParams.pageNum = val
      this.getAttach()
      this.$forceUpdate()
    },
    getAttach() {
      attachPage(this.queryParams).then(response => {
        this.queryParams.total = response.total
        this.dataSource = response.rows
      })
    },
    editImageCategory() {
      this.$prompt('请输入分组名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: this.category.name
      }).then(({value}) => {
        updateAttachCate({id: this.category.id, name: value}).then(res => {
          this.$message.success('重命名成功')
          this.category.name = value
          this.$set(this.imgCategory, this.category.index, this.category)
        })
      })
    },
    removeImageCategory() {
      this.$confirm('删除分组后会同时删除分组下的所有图片，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delAttachCate(this.category.id).then(res => {
          this.$delete(this.imgCategory, this.category.index)
          this.$message.success('删除成功')
          this.getCategory()
        })
      })
    },
    beforeUpload(file) {
      const isPic =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'image/jpg' ||
        file.type === 'video/mp4'
      const isLt2M = file.size / 1024 / 1024 < 300
      if (!isPic) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG、GIF、MP4 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 300MB!')
      }
      return isPic && isLt2M
    },
    handleSuccess(response, file, fileList) {
      let data = {
        filename: file.name,
        path: response.url,
        cateId: this.category.id
      }
      addAttach(data).then(res => {
        this.getAttach()
      })
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>
<style scoped>
.li-item {
  width: 150px;
  height: 150px;
}

.img-card-box {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.img-card-item {
  display: inline-block;
  margin: 0 5px;
  width: 150px;
  height: 200px;
}

.card-footer {
  width: 100%;
  height: 30px;
  text-align: center;
  margin-top: 40px;
}

.tab-pane-box {
  padding-top: 30px;
  width: 100%;
  height: 525px;
  background-color: #eef1f6;
  overflow: auto;
}
</style>
